package cn.jtfadmin.base.data.jpa.domain.entity;

import cn.jtfadmin.base.lang.common.domain.entity.EntityListener;
import cn.jtfadmin.base.lang.config.ApplicationHolder;
import org.springframework.context.ApplicationContext;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

/**
 * 实体监听器
 */
public class DefaultEntityListener implements EntityListener, Serializable {


    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    @PrePersist
    public void prePersist(Object object) {
        for (EntityListener entityListener : getEntityListeners()) {
            entityListener.prePersist(object);
        }
    }

    @Override
    @PreUpdate
    public void preUpdate(Object object) {
        for (EntityListener entityListener : getEntityListeners()) {
            entityListener.preUpdate(object);
        }
    }

    @Override
    @PreRemove
    public void preRemove(Object object) {
        for (EntityListener entityListener : getEntityListeners()) {
            entityListener.preRemove(object);
        }
    }

    @Override
    @PostPersist
    public void postPersist(Object object) {
        for (EntityListener entityListener : getEntityListeners()) {
            entityListener.postPersist(object);
        }
    }

    @Override
    @PostUpdate
    public void postUpdate(Object object) {
        for (EntityListener entityListener : getEntityListeners()) {
            entityListener.postUpdate(object);
        }
    }

    @Override
    @PostRemove
    public void postRemove(Object object) {
        for (EntityListener entityListener : getEntityListeners()) {
            entityListener.postRemove(object);
        }
    }

    @Override
    @PostLoad
    public void postLoad(Object object) {
        for (EntityListener entityListener : getEntityListeners()) {
            entityListener.postLoad(object);
        }
    }

    protected EntityListener[] getEntityListeners() {
        ApplicationContext applicationContext = ApplicationHolder.getApplicationContext();
        String[] beanNames = applicationContext.getBeanNamesForType(EntityListener.class);
        if (Objects.isNull(beanNames)) {
            return new EntityListener[0];
        }
        EntityListener[] listeners = new EntityListener[beanNames.length];
        for (int i = 0; i < beanNames.length; i++) {
            listeners[i] = applicationContext.getBean(beanNames[i], EntityListener.class);
        }
        return listeners;
    }


}
